import React from 'react'
import {Button, Card, Form, Input, Spin} from 'antd'
import {withRouter} from 'react-router-dom'
import {connect} from 'react-redux'
import {TwsReactMarkdownEditor} from 'tws-antd'
import {formItemLayout, mdLayout} from '../../constant/constant-style'
import * as actions from '../../actions/stack'
import {getUploadUrl} from '../../constant/upload-url'
import '../../less/index.less'
import {FormattedMessage} from 'react-intl'
import {convertContent} from '../../constant/lang-util'

const FormItem = Form.Item
class AddOrEditStacks extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      description: '',
      descriptionError: '',
      imageStatus: '',
      isShowSpin: false
    }
  }

  handleSubmit () {
    const {description} = this.state
    const {form} = this.props
    if (!description) {
      this.setState({descriptionError: '描述不能为空'})
      return
    }
    this.setState({isShowSpin: true})

    form.validateFields((err, values) => {
      if (!err) {
        values = Object.assign({}, values, {description})
        this.props.addStack(values, ()=>{
          this.setState({isShowSpin: false})
        })
      }
    })
  }

  render () {
    const {getFieldDecorator} = this.props.form
    const {settings} = this.props
    const {isShowSpin} = this.state

    return (<Form>
      <FormItem {...mdLayout} label={<FormattedMessage id='技术栈描述' />} required>
        <TwsReactMarkdownEditor
          action={getUploadUrl(settings.appContextPath)}
          value={this.state.description}
          onChange={(description) => this.setState({description})} />
        <div className='error-tip'>{convertContent(this.state.descriptionError)}</div>
      </FormItem>
      <FormItem {...formItemLayout} label='image'>
        {getFieldDecorator('image', {
          rules: [{
            required: true, message: <FormattedMessage id='请输入image,格式如：node:8-alpine' />
          }]
        })(
          <Input style={{width: '100%'}} />
        )}

      </FormItem>
      <FormItem wrapperCol={{span: 20, offset: 2}}>
        <div className='gray'>
          {isShowSpin ?
          <Card style={{width: '100%'}}>
            <div><Spin /><span className='yellow'><FormattedMessage id='请稍等...' /></span></div>
          </Card>
            : ''}
          </div>
      </FormItem>
      <FormItem wrapperCol={{span: 8, offset: 8}}>
        <Button type='primary' onClick={this.handleSubmit.bind(this)}><FormattedMessage id='添加' /></Button>
      </FormItem>
    </Form>)
  }
}

const mapStateToProps = ({stackData, settings}) => ({
  stackStatus: stackData.status,
  logsData: stackData.logs,
  stack: stackData.stack,
  settings
})

const mapDispatchToProps = (dispatch) => ({
  addStack: (stack, callback) => dispatch(actions.addStack(stack, callback)),
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Form.create()(AddOrEditStacks)))
